package com.sunyard.base.base


import android.content.Context
import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import androidx.annotation.DrawableRes
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.LogUtils
import com.hjq.bar.OnTitleBarListener
import com.hjq.bar.TitleBar
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.sunyard.base.ktExt.getViewModel
import com.sunyard.base.ktExt.getViewModelBindActivity

import com.sunyard.base.ktExt.toast
import com.sunyard.base.viewModel.BaseViewModel
import com.sunyard.base.widget.StatusManager
import kotlinx.android.synthetic.main.demo_item_view_pager2.*


/**
 * A simple [Fragment] subclass.
 */
 abstract class BaseFragment<T: BaseViewModel> : Fragment(),OnTitleBarListener {

    var titleBar: TitleBar?=null
    override fun onLeftClick(v: View?) {
        activity?.onBackPressed()
    }

    override fun onRightClick(v: View?) {

    }

    override fun onTitleClick(v: View?) {

    }
    var rootView:View?=null
    var layoutId: Int? = null
    // 根布局
    var layoutView: View? = null
    var viewModel:T?=null
    var bundle:Bundle?=null

    // 是否进行过懒加载
    private var isLazyLoad: Boolean = false
    // Fragment 是否可见
    private var isFragmentVisible: Boolean = false
    // 是否是 replace Fragment 的形式
    private var isReplaceFragment: Boolean = false

    /**
     * 初始化变量过后再走这边
     * */
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        hideSoftKeyboard()
        bundle=savedInstanceState
        layoutId = initLayout()
        layoutView = initLayoutView()

        if (layoutView == null && initLayout()!=null) {
            layoutView = inflater.inflate(initLayout()!!, null)
        }
        if(container?.parent!=null){
            val parent = container.parent as ViewGroup
            parent.removeView(layoutView)
        }

        LogUtils.d("初始化 Fragment${javaClass.name}")
        viewModel = if (!viewModelIsBindActivity()) {
            getViewModel(initViewModel())
        }else{
            getViewModelBindActivity(initViewModel())
        }

        return layoutView
    }



    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        rootView=view
        if (isReplaceFragment) {
            if (isFragmentVisible) {
                initLazyLoad()
            }
        } else {
            initLazyLoad()
        }
        initTitleBar()
        if (needShowMsg()){
            initMsgLiveData()
            initCodeLiveData()
        }
        initLiveData()
        initView()

    }
    open fun needShowMsg()=true
    private fun initMsgLiveData() {
        viewModel?.msg?.observe(viewLifecycleOwner, Observer {
            if (!viewModel?.showMsgOK?.value!!) {
                toast(it)
                viewModel?.showMsgOK?.value=true
            }
            showComplete()
            stopLoadMoreRefresh()
        })
    }
    private fun initCodeLiveData(){
        viewModel?.code?.observe(this, Observer {
            if (!viewModel?.showCodeOK?.value!!) {
                showError()
                viewModel?.showCodeOK?.value=true
            }
        })
    }

    /**
     * 如果由需要，重写此方法 初始化layoutView,最后一步
     * */
    private fun initLayoutView(): View? {
        return null
    }

    /**
     * 返回layout布局
     * */
    abstract fun initLayout(): Int?

    /**
     * 初始化viewModel
     * */
    abstract fun initViewModel(): Class<T>

    /**
     * 初始化对liveData的监听处理
     * */
    abstract fun initLiveData()

    /**
     * 初始化组件响应事件
     * */
    abstract fun initView()

    open fun viewModelIsBindActivity()=false


    /**
     * 隐藏软键盘
     */
    private fun hideSoftKeyboard() {
        // 隐藏软键盘，避免软键盘引发的内存泄露
        val view = activity?.currentFocus
        if (view != null) {
            val manager =
                activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
            view.post {
                manager?.hideSoftInputFromWindow(view.windowToken, 0)
            }
        }
    }

    fun <K> startActivity(cls : Class<K>){
        val intent= Intent()
        intent.setClass(context!!,cls)
        startActivity(intent)
    }


    fun <K> startActivity(cls: Class<K>, data: String) {
        val intent = Intent()
        intent.setClass(context!!, cls)
        intent.putExtra("data", data)
        startActivity(intent)
    }


    /**
     * 是否进行了懒加载
     */
    protected fun isLazyLoad(): Boolean {
        return isLazyLoad
    }

    /**
     * 当前 Fragment 是否可见
     */
    fun isFragmentVisible(): Boolean {
        return isFragmentVisible
    }

    // replace Fragment 时使用，ViewPager 切换时会回调此方法
    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        this.isReplaceFragment = true
        this.isFragmentVisible = isVisibleToUser
        if (isVisibleToUser && mLayoutRoot != null) {
            if (!isLazyLoad) {
                initLazyLoad()
            } else {
                // 从不可见到可见
                onRestart()
            }
        }
    }

    /**
     * 初始化懒加载
     */
    protected fun initLazyLoad() {
        if (!isLazyLoad) {
            isLazyLoad = true
//            initView()
        }
    }

    /**
     * 从可见的状态变成不可见状态，再从不可见状态变成可见状态时回调
     */
    protected fun onRestart() {}

//    override fun onDetach() {
//        super.onDetach()
//        // 解决java.lang.IllegalStateException: Activity has been destroyed 的错误
//        try {
//            val childFragmentManager =
//                Fragment::class.java.getDeclaredField("mChildFragmentManager")
//            childFragmentManager.isAccessible = true
//            childFragmentManager.set(this, null)
//        } catch (e: NoSuchFieldException) {
//            throw RuntimeException(e)
//        } catch (e: IllegalAccessException) {
//            throw RuntimeException(e)
//        }
//
//    }

    private val mStatusManager = StatusManager()
    /**
     * 显示加载中
     */
    fun showLoading() {
        mStatusManager.showLoading(activity!!)
    }

    /**
     * 显示加载完成
     */
    fun showComplete() {
        mStatusManager.showComplete()
    }

    /**
     * 显示空提示
     */
    fun showEmpty() {
        mStatusManager.showEmpty(rootView!!)
    }

    /**
     * 显示错误提示
     */
    fun showError() {
        mStatusManager.showError(rootView!!)
    }

    /**
     * 显示自定义提示
     */
    fun showLayout(@DrawableRes iconId: Int, textStr: String) {
        mStatusManager.showLayout(rootView!!, iconId, textStr)
    }

    fun showLayout(drawable: Drawable, hint: CharSequence) {
        mStatusManager.showLayout(rootView!!, drawable, hint)
    }

    // 加载布局
    private var mSmartRefreshLayout: SmartRefreshLayout? = null
    fun initSwipeRefresh(listener: OnRefreshLoadMoreListener) {
        showComplete()
        val view:View= layoutView!!
        if (mSmartRefreshLayout == null) {
            if (view is SmartRefreshLayout) {
                mSmartRefreshLayout = view
            } else if (view is ViewGroup) {
                mSmartRefreshLayout = findSmartRefreshLayout(view)
            }

//            LogUtils.e("You didn't add this SmartRefreshLayout to your Fragment layout")
//            checkNotNull(mSmartRefreshLayout) { "You didn't add this SmartRefreshLayout to your Fragment layout" }
        }

        mSmartRefreshLayout?.setOnRefreshLoadMoreListener(object :OnRefreshLoadMoreListener{
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                listener.onLoadMore(refreshLayout)
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                listener.onRefresh(refreshLayout)
            }
        })
    }
    fun closeLoadMore(isClose:Boolean){
        mSmartRefreshLayout?.setEnableLoadMore(isClose)
    }
    fun closeRefresh(isClose:Boolean){
        mSmartRefreshLayout?.setEnableRefresh(isClose)
    }
    fun stopLoadMoreRefresh(){
        mSmartRefreshLayout?.finishLoadMore()
        mSmartRefreshLayout?.finishRefresh()
    }


    /**
     * 智能获取布局中的 SwipeRefreshLayout 对象
     */
    private fun findSmartRefreshLayout(group: ViewGroup): SmartRefreshLayout? {
        for (i in 0 until group.childCount) {
            val view = group.getChildAt(i)
            if (view is SmartRefreshLayout) {
                return view
            } else if (view is ViewGroup) {
                val layout = findSmartRefreshLayout(view)
                if (layout != null) return layout
            }
        }
        return null
    }

    fun initTitleBar() {

        val view:View=layoutView!!
        if (titleBar == null) {

            if (view is TitleBar) {
                titleBar = view
            } else if (view is ViewGroup) {
                titleBar = findTitleBar(view)
            }
//            LogUtils.e("You didn't add this titleBar to your Activity layout")
//            checkNotNull(titleBar) { "You didn't add this titleBar to your Activity layout" }
        }
        titleBar?.setOnTitleBarListener(this)
    }


    /**
     * 智能获取布局中的 SwipeRefreshLayout 对象
     */
    private fun findTitleBar(group: ViewGroup): TitleBar? {
        for (i in 0 until group.childCount) {
            val view = group.getChildAt(i)
            if (view is TitleBar) {
                return view
            } else if (view is ViewGroup) {
                val titleBar = findTitleBar(view)
                if (titleBar != null) return titleBar
            }
        }
        return null
    }

    override fun onStart() {
        super.onStart()

    }

    override fun onStop() {
        super.onStop()

    }


}
